package com.yangcsoft.modules.deptmanage.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yangcsoft.common.utils.DateUtils;
import com.yangcsoft.common.utils.ExcelUtil;
import com.yangcsoft.common.utils.PageUtils;
import com.yangcsoft.common.utils.R;
import com.yangcsoft.common.validator.ValidatorUtils;
import com.yangcsoft.modules.deptmanage.entity.StaffInfoEntity;
import com.yangcsoft.modules.deptmanage.service.StaffInfoService;
import com.yangcsoft.modules.sys.service.SysDictService;
import com.yangcsoft.modules.sys.shiro.ShiroUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;


/**
 * 员工信息表
 *
 * @author XueQing Wang
 * @email 17621152225@163.com
 * @date 2019-05-02 14:22:45
 */
@RestController
@RequestMapping("deptmanage/staffinfo")
public class StaffInfoController {
    @Autowired
    private StaffInfoService staffInfoService;
    @Autowired
    private SysDictService sysDictService;
    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("deptmanage:staffinfo:list")
    public R list(@RequestParam Map<String, Object> params) {
        String key = "";
        Object keyObj = params.get("key");
        if (keyObj != null) {
            key = keyObj.toString();
        }
        params.put("key", key);
        PageUtils page = staffInfoService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{userseq}")
    @RequiresPermissions("deptmanage:staffinfo:info")
    public R info(@PathVariable("userseq") String userseq) {
        StaffInfoEntity staffInfo = staffInfoService.selectById(userseq);

        return R.ok().put("staffInfo", staffInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("deptmanage:staffinfo:save")
    public R save(@RequestBody StaffInfoEntity staffInfo) {
        staffInfo.setCreateDate(DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        staffInfo.setCreateUser(ShiroUtils.getUserEntity().getUsername());
        staffInfoService.save(staffInfo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("deptmanage:staffinfo:update")
    public R update(@RequestBody StaffInfoEntity staffInfo) {
        ValidatorUtils.validateEntity(staffInfo);
        staffInfo.setUpdateDate(DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        staffInfo.setUpdateUser(ShiroUtils.getUserEntity().getUsername());
        staffInfoService.updateAllColumnById(staffInfo);//全部更新

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("deptmanage:staffinfo:delete")
    public R delete(@RequestBody String[] userseqs) {
        staffInfoService.deleteBatchIds(Arrays.asList(userseqs));

        return R.ok();
    }

    /**
     * 导出报表
     *
     * @param response
     * @return
     */
    @RequestMapping("/export")
    public R export(Long[] ids, HttpServletResponse response, HttpServletRequest request) {
        String[] secondTitles = null;
        String[] beanProperty = null;
        String title = null;
        secondTitles = new String[]{
                "人员序号",
                "人员姓名",
                "性别",
                "出生日期",
                "证件类型",
                "证件号码",
                "婚姻状态（已婚，未婚，丧偶，离婚，再婚）",
                "民族",
                "籍贯",
                "居住地",
                "入职日期",
                "转正日期",
                "使用工资",
                "转正工资",
                "社保状态（新开，续缴，跨地转移，不缴）",
                "公积金（新开，转移，不缴）",
                "参加工作日期",
                "健康状况",
                "学位",
                "学历",
                "政治面貌",
                "职务级别",
                "人员状态（在职，实习，离职，试用）",
                "紧急联系人",
                "紧急联系人电话",
                "创建日期",
                "创建人",
                "修改日期",
                "修改人"
        };
        beanProperty = new String[]{
                "userseq",
                "username",
                "gender",
                "birthday",
                "idType",
                "idNo",
                "marriage",
                "nation",
                "nativePlace",
                "birthPlace",
                "joinPartyDate",
                "normalPartyDate",
                "testSalary",
                "normalSalary",
                "socialInsuranceStatus",
                "accumulationFund",
                "participationDate",
                "healthy",
                "academicDegree",
                "educationLevel",
                "political",
                "jobLevel",
                "userstatus",
                "emergencyContact",
                "emergencyContactTel",
                "createDate",
                "createUser",
                "updateDate",
                "updateUser"
        };
        title = "员工信息表报表";

        List<StaffInfoEntity> list = staffInfoService.selectList(new EntityWrapper<>());
        Map<String,String> gender = sysDictService.selectExportDictMap("gender");
        Map<String,String> marriage = sysDictService.selectExportDictMap("marriage");
        Map<String,String> socialInsuranceStatus = sysDictService.selectExportDictMap("socialInsuranceStatus");
        Map<String,String> accumulationFund = sysDictService.selectExportDictMap("accumulationFund");
        Map<String,String> jobLevel = sysDictService.selectExportDictMap("jobLevel");
        Map<String,String> userstatus = sysDictService.selectExportDictMap("userstatus");
        for (StaffInfoEntity entity : list) {
            entity.setGender(gender.get(entity.getGender()));
            entity.setMarriage(marriage.get(entity.getMarriage()));
            entity.setSocialInsuranceStatus(socialInsuranceStatus.get(entity.getSocialInsuranceStatus()));
            entity.setAccumulationFund(accumulationFund.get(entity.getAccumulationFund()));
            entity.setJobLevel(jobLevel.get(entity.getJobLevel()));
            entity.setUserstatus(userstatus.get(entity.getUserstatus()));
        }

        File file = ExcelUtil.exportResult(request, list, title, secondTitles, beanProperty);
        try {
            response.setContentType("application/x-download");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(title.getBytes("gbk"), "iso8859-1") + ".xls");
            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream fileInputStream = new FileInputStream(file);
            IOUtils.copy(fileInputStream, outputStream);
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    /**
     * 导入报表
     *
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/batchImport")
    public R batchImport(HttpServletResponse response, MultipartFile file) throws Exception {
        String[] beanProperty = null;
        beanProperty = new String[]{
                "username",
                "gender",
                "birthday",
                "idType",
                "idNo",
                "marriage",
                "nation",
                "nativePlace",
                "birthPlace",
                "joinPartyDate",
                "normalPartyDate",
                "testSalary",
                "normalSalary",
                "socialInsuranceStatus",
                "accumulationFund",
                "participationDate",
                "healthy",
                "academicDegree",
                "educationLevel",
                "political",
                "jobLevel",
                "userstatus",
                "emergencyContact",
                "emergencyContactTel"
        };
        List<StaffInfoEntity> list = ExcelUtil.parserExcel(StaffInfoEntity.class, file, beanProperty);
        Map<String,String> gender = sysDictService.selectDictMap("gender");
        Map<String,String> marriage = sysDictService.selectDictMap("marriage");
        Map<String,String> socialInsuranceStatus = sysDictService.selectDictMap("socialInsuranceStatus");
        Map<String,String> accumulationFund = sysDictService.selectDictMap("accumulationFund");
        Map<String,String> jobLevel = sysDictService.selectDictMap("jobLevel");
        Map<String,String> userstatus = sysDictService.selectDictMap("userstatus");
        for (StaffInfoEntity entity : list) {
            entity.setGender(gender.get(entity.getGender()));
            entity.setMarriage(marriage.get(entity.getMarriage()));
            entity.setSocialInsuranceStatus(socialInsuranceStatus.get(entity.getSocialInsuranceStatus()));
            entity.setAccumulationFund(accumulationFund.get(entity.getAccumulationFund()));
            entity.setJobLevel(jobLevel.get(entity.getJobLevel()));
            entity.setUserstatus(userstatus.get(entity.getUserstatus()));
            save(entity);
        }
        return R.ok();
    }

    /**
     * 下载导入模版
     */
    @RequestMapping("/templateDownload")
    public R exportXls(HttpServletResponse response) {
        String title = "员工信息表录入模版";
        String[] secondTitles = new String[]{
                "人员姓名",
                "性别",
                "出生日期",
                "证件类型",
                "证件号码",
                "婚姻状态（已婚，未婚，丧偶，离婚，再婚）",
                "民族",
                "籍贯",
                "居住地",
                "入职日期",
                "转正日期",
                "使用工资",
                "转正工资",
                "社保状态（新开，续缴，跨地转移，不缴）",
                "公积金（新开，转移，不缴）",
                "参加工作日期",
                "健康状况",
                "学位",
                "学历",
                "政治面貌",
                "职务级别",
                "人员状态（在职，实习，离职，试用）",
                "紧急联系人",
                "紧急联系人电话"
        };

        Integer startRow = 0;
        Integer endRow = 0;
        Integer startCol = 0;
        Integer endCol = 0;

        HSSFWorkbook workbook = ExcelUtil.createWorkBook(response,title,title,secondTitles);
        workbook = ExcelUtil.setValidationCell(workbook, sysDictService.selectDictListByCode("gender"),1,100,1,1);
        workbook = ExcelUtil.setValidationCell(workbook, sysDictService.selectDictListByCode("marriage"),1,100,5,5);
        workbook = ExcelUtil.setValidationCell(workbook, sysDictService.selectDictListByCode("socialInsuranceStatus"),1,100,13,13);
        workbook = ExcelUtil.setValidationCell(workbook, sysDictService.selectDictListByCode("accumulationFund"),1,100,14,14);
        workbook = ExcelUtil.setValidationCell(workbook, sysDictService.selectDictListByCode("jobLevel"),1,100,20,20);
        workbook = ExcelUtil.setValidationCell(workbook, sysDictService.selectDictListByCode("userstatus"),1,100,21,21);
        ExcelUtil.templateDownload(response,workbook,secondTitles,startRow,endRow,startCol,endCol);

//        ExcelUtil.templateDownload(response, title, title, secondTitles, new ArrayList<>(), startRow, endRow, startCol, endCol);

        return R.ok();
    }

}
